package com.xcd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xcd.reggie.common.R;
import com.xcd.reggie.entity.ShoppingCart;
import com.xcd.reggie.entity.User;
import com.xcd.reggie.service.UserService;
import com.xcd.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("code= {}", code);
        httpSession.setAttribute(user.getPhone(), code);
        return R.success("验证码生成成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession httpSession) {
        //获取手机号
        String phone = map.get("phone");

        //获取验证码
        String code = map.get("code");

        String codeInSession = httpSession.getAttribute(phone).toString();
        //验证码对比
        if (code != null && codeInSession.equals(code)) {

            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(lambdaQueryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);

            }
            httpSession.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登陆失败");
    }
    @PostMapping("/loginout")
    public  R<String> loginOut(HttpSession httpSession){
        httpSession.removeAttribute("user");
        return R.success("退出成功");

    }


}
